import axios from 'axios';
import { Message } from 'element-ui';
import { getCookie } from '../plugins/utils';

axios.defaults.baseURL = '/college';
axios.defaults.timeout = 30000;
axios.defaults.withCredentials = true;
axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';

// 请求拦截器
axios.interceptors.request.use(
    req => {
        const USER_TOKEN = getCookie('USER_TOKEN');
        // 登录后，添加token
        if(USER_TOKEN){
            req.headers.common['Authorization'] = 'bearer ' + USER_TOKEN
        }
        return req
    },
    err => {
        return Promise.reject(err)
    }
);

// 响应拦截器
axios.interceptors.response.use(
    res => {
        if(res.status === 200){
            return res.data
        }
        return res
    },
    err => {
        const { response: { status, statusText, data } } = err;
        if(status === 401){
            switch (statusText) {
                case 'Unauthorized': {
                    Message({
                        type: 'error',
                        message: data.error
                    });
                    break
                }
                default: {

                }
            }
        }else {
            Message({
                type: 'error',
                message: '服务器内部错误，请重试'
            })
        }
        return Promise.reject(err)
    }
);

export default axios;